package cn.iot.sys.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.iot.common.dto.ResultMsg;
import cn.iot.sys.dao.SysClassDao;
import cn.iot.sys.entity.SysClass;
import cn.iot.sys.entity.SysGrade;
import cn.iot.sys.service.SysClassService;
import cn.iot.sys.service.SysGradeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SysClassServiceImpl implements SysClassService {
    @Resource
    private SysClassDao sysClassDao;
    public Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private SysGradeService sysGradeService;

    @Override
    public ResultMsg getSysClassList(Map<String, Object> params) {
        logger.info("SysClassServiceImpl getSysClassList params{}",params);
        int pageSize = Integer.parseInt(String.valueOf(params.get("pageSize")));
        int pageNum = Integer.parseInt(String.valueOf(params.get("pageNum")));

        int major_id = Integer.parseInt(String.valueOf(params.get("major_id")));
        int status = Integer.parseInt(String.valueOf(params.get("status")));

        int start = (pageNum-1)*pageSize;
        params.remove("pageSize");
        params.put("pageSize",pageSize);
        params.put("start",start);
        params.remove("major_id");
        params.put("major_id",major_id);
        params.remove("status");
        params.put("status",status);

        List<SysClass> sysClassList = sysClassDao.getSysClassList(params);
        int count = sysClassDao.getSysClassCount(params);
        int pageCount;
        if (count>0){
            pageCount = count%pageSize==0? count/pageSize:count/pageSize+1;
        }else {
            pageCount = 0;
        }
        params.put("sysClassList",sysClassList);
        params.put("pageCount",pageCount);
        ResultMsg msg = new ResultMsg(200,"成功",params);
        return msg;
    }

    @Transactional
    @Override
    public ResultMsg addSysClass(SysClass sysClass) {
        logger.info("SysClassServiceImpl getSysClassList sysClass{}",sysClass);
        int count = sysClassDao.addSysClass(sysClass);
        if (count>0){
            return new ResultMsg(200,"成功",null);
        }
        return new ResultMsg(500,"失败",null);
    }

    @Override
    public ResultMsg delSysClassById(int id) {
        logger.info("SysClassServiceImpl delSysClassById id{}",id);
        int count = sysClassDao.delSysClassById(id);
        if (count>0){
            return new ResultMsg(200,"成功",null);
        }
        return new ResultMsg(500,"失败",null);
    }

    @Override
    public ResultMsg getSysClass() {
        logger.info("SysClassServiceImpl getSysClass start ...");
        List<SysClass> sysClass = sysClassDao.getSysClass();
        ResultMsg msg = new ResultMsg(200,"成功",sysClass);
        return msg;
    }

    @Override
    public ResultMsg viewSysClassById(int id) {
        logger.info("SysClassServiceImpl viewSysClassById id{}",id);
        SysClass sysClass = sysClassDao.viewSysClassById(id);
        ResultMsg msg = new ResultMsg(200,"成功",sysClass);
        return msg;
    }

    @Transactional
    @Override
    public ResultMsg updSysClassById(SysClass sysClass) {
        logger.info("SysClassServiceImpl updSysClassById sysClass{}",sysClass);
        int count= sysClassDao.updSysClassById(sysClass);
        if (count>0){
            return new ResultMsg(200,"成功",null);
        }
        return new ResultMsg(500,"失败",null);
    }

    @Override
    public ResultMsg updStatusById(SysClass sysClass) {
        logger.info("SysClassServiceImpl updStatusById sysClass{}",sysClass);
        if (sysClass.getStatus()==1){
            sysClass.setStatus(0);
        }else {
            sysClass.setStatus(1);
        }
        int count = sysClassDao.updStatusById(sysClass);
        if (count>0){
            return new ResultMsg(200,"成功",null);
        }
        return new ResultMsg(500,"失败",null);
    }

    @Override
    public ResultMsg getClassByName(String name) {
        logger.info("SysClassServiceImpl getClassByName name{}",name);
        int count = sysClassDao.getClassByName(name);
        if (count>0){
            return new ResultMsg(200,"成功",null);
        }
        return new ResultMsg(500,"失败",null);
    }

    @Override
    public ResultMsg uploadClassInfo(MultipartFile file) {
        List<SysClass> classInfoList = new ArrayList<>();
        List<String> errorMessages = new ArrayList<>();

        try (InputStream inputStream = file.getInputStream()) {
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);

            for (int i = 2; i <= sheet.getLastRowNum(); i++) { // 从第2行开始，跳过表头
                Row row = sheet.getRow(i);
                if (row != null) {
                    String className = row.getCell(0).getStringCellValue();
                    String gradeName = row.getCell(1).getStringCellValue();  // 改为从年级名获取

                    // 校验年级名是否正确
                    ResultMsg msg =sysGradeService.getGradeByName(gradeName);
                    if (msg.getStatus() != 200) {
                        errorMessages.add("第 " + (i + 1) + " 行的年级名 '" + gradeName + "' 不存在！");
                        continue; // 跳过该行
                    }
                    int gradeId = ((SysGrade) msg.getData()).getId(); // 获取年级ID

                    // 校验班级名是否重复
                    ResultMsg msg1 = this.getClassByName(className);
                    if (msg1.getStatus() == 200) {
                        errorMessages.add("第 " + (i + 1) + " 行的班级名 '" + className + "' 已经存在！");
                        continue; // 跳过该行
                    }

                    // 创建班级信息对象
                    SysClass sysClass = new SysClass();
                    sysClass.setGradeId(gradeId);
                    sysClass.setName(className);
                    classInfoList.add(sysClass);
                }
            }

            // 如果有错误，返回错误信息
            if (!errorMessages.isEmpty()) {
                return new ResultMsg(400, "部分数据有误，请检查并修改。", errorMessages);
            }

            // 如果所有数据都正确，保存班级信息到数据库
            for (SysClass sysClass : classInfoList) {
                addSysClass(sysClass);

            }

            return new ResultMsg(200, "文件上传并处理成功。", null);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResultMsg(500, "文件上传失败。", null);
        }
    }

    @Override
    public ResultMsg getSysClassByName(String name) {
        logger.info("SysClassServiceImpl getSysClassByName name{}",name);
        SysClass sysClass = sysClassDao.getSysClassByName(name);
        if (sysClass != null){
            return new ResultMsg(200,"成功",null);
        }
        return new ResultMsg(500,"失败",null);
    }
}
